package cn.mdmbct.douyin.common.redis;

import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.util.Pool;

import java.util.concurrent.TimeUnit;

/**
 * Jedis操作Redis
 *
 * @author mdmbct  mdmbct@outlook.com
 * @date 2021/3/18 0:04
 * @modified mdmbct
 * @since 1.0
 */
@RequiredArgsConstructor
public class JedisOps implements DyRedisOps {

    private final Pool<Jedis> jedisPool;


    @Override
    public <T> T getValue(String key, Class<T> valueClass) {
        return JSONObject.parseObject(jedisPool.getResource().get(key), valueClass);
    }

    @Override
    public <T> void setValue(String key, T value, long expire, TimeUnit timeUnit) {
        if (expire <= 0) {
            setValue(key, value);
        } else {
            jedisPool.getResource().psetex(key, timeUnit.toMillis(expire), JSONObject.toJSONString(value));
        }
    }

    @Override
    public <T> void setValue(String key, T value) {
        jedisPool.getResource().set(key, JSONObject.toJSONString(value));
    }

    @Override
    public Long getExpire(String key) {
        return jedisPool.getResource().ttl(key);
    }

    @Override
    public void setExpire(String key, long expire, TimeUnit timeUnit) {
        jedisPool.getResource().pexpire(key, timeUnit.toMillis(expire));
    }
}
